package com.fmatos.amazingwallpapers.image.database.orm;

import javax.inject.Inject;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
	private static final String TAG = DatabaseHelper.class.getSimpleName();
	
	// name of the database file for your application -- change to something appropriate for your app
	private static final String DATABASE_NAME = "albums.sqlite";

	// any time you make changes to your database objects, you may have to increase the database version
	private static final int DATABASE_VERSION = 11;



	private Dao<Album, String> albumDao = null;
	private Dao<Photo, String> photoDao = null;

	@Inject
	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		Log.i(TAG,"Database helper constructor running");
	}

	@Override
	public void onCreate(SQLiteDatabase database,ConnectionSource connectionSource) {
		try {
			TableUtils.createTable(connectionSource, Album.class);
			TableUtils.createTable(connectionSource, Photo.class);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
			throw new RuntimeException(e);
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db,ConnectionSource connectionSource, int oldVersion, int newVersion) {
		
		try {
			TableUtils.dropTable(connectionSource, Album.class, true);
			TableUtils.dropTable(connectionSource, Photo.class, true);
			onCreate(db, connectionSource);
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
		
	}

	@Deprecated
	public Dao<Album, String> getAlbumDao() {
		if (null == albumDao) {
			try {
				albumDao = getDao(Album.class);
			}catch (java.sql.SQLException e) {
				e.printStackTrace();
			}
		}
		return albumDao;
	}

	@Deprecated
	public Dao<Photo, String> getPhotoDao() {
		if (null == photoDao) {
			try {
				photoDao = getDao(Photo.class);
			}catch (java.sql.SQLException e) {
				e.printStackTrace();
			}
		}
		return photoDao;
	}

}
